import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import { useRef, useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import {
  addHistoryActionCreator,
  clearHistoryActionCreator,
  clearSuggestionActionCreator,
  getSuggestionActionCreator,
} from '@/store/action/search';
import { useAppSelector } from '@/store';
import DOMPurify from 'dompurify';
import classNames from 'classnames';
import { Toast } from 'antd-mobile';
import { removeHistory } from '@/utils/storage';
import history from '@/utils/history';

export default function Search() {
  // 利用正则替换高亮关键字
  const highlight = (str: string, key: string) => {
    // g表示全部匹配
    // i表示忽略大小写
    // 根据传入的变量创建正则对象
    const reg = new RegExp(`${key}`, 'gi');
    // 替换高亮文字
    return str.replace(reg, `<span>${keyWord}</span>`);
  };
  const dispatch = useDispatch();
  // 获取搜索建议数据
  const { suggestion } = useAppSelector((state) => state.search);
  // 获取搜索历史
  const { histories } = useAppSelector((state) => state.search);

  // 搜索关键字
  const [keyWord, setKeyWord] = useState('');

  // 互斥搜索建议和搜索历史
  const [isSearching, setIsSearching] = useState(false);

  // 清空输入框的值
  const onClear = () => {
    // 清空输入框内容
    setKeyWord('');
    // 设置为显示历史记录状态
    setIsSearching(false);
    // 清空redux里面的搜索建议
    dispatch(clearSuggestionActionCreator());
  };

  // 点击搜索按钮
  const handleSearch = () => {
    if (!keyWord.trim()) return Toast.show({ content: '请输入搜索内容' });
    dispatch(addHistoryActionCreator(keyWord));
    // 跳转到搜索页
    gotoSearchResultPage(keyWord);
  };

  // 点击清空全部搜索记录
  const handleClearHistory = () => {
    // 删除全部的历史搜索记录
    dispatch(clearHistoryActionCreator());
    // 清空本地数据
    removeHistory();
  };

  // 去搜索结果页
  const gotoSearchResultPage = (keyWord: string) => {
    // 把关键字添加到历史记录中
    dispatch(addHistoryActionCreator(keyWord));
    // 跳转到搜索结果页
    history.push(`/search/result?q=${keyWord}`);
  };

  //1. 防抖处理
  const timerId = useRef(-1);
  // 绑定跟新表单值
  const handleChange = (value: string) => {
    // 更新表单值
    setKeyWord(value);
    setIsSearching(true);
    window.clearTimeout(timerId.current);
    // 2.防抖步骤2：用户操作500ms后再发送请求
    timerId.current = window.setTimeout(() => {
      if (!value) return;
      // 根据关键字发送请求
      dispatch(getSuggestionActionCreator(value));
    }, 500);
  };

  // 养成习惯，组件卸载清理计时器
  useEffect(() => {
    return () => {
      window.clearInterval(timerId.current);
    };
  }, []);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        right={
          <span className="search-text" onClick={handleSearch}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              type="text"
              placeholder="请输入关键字搜索"
              value={keyWord}
              onChange={(e) => handleChange(e.target.value.trim())}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            />

            {/* 清空输入框按钮 */}
            <Icon
              type="iconbtn_tag_close"
              className="icon-close"
              onClick={onClear}
            />
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      <div
        className="history"
        style={{ display: isSearching ? 'none' : 'block' }}
      >
        <div className="history-header">
          <span>搜索历史</span>
          <span onClick={handleClearHistory}>
            <Icon type="iconbtn_del" />
            清除全部
          </span>
        </div>

        <div className="history-list">
          {histories.map((item: string, index: number) => (
            <span
              className="history-item"
              key={index}
              onClick={() => gotoSearchResultPage(item)}
            >
              {item}
              <span className="divider"></span>
            </span>
          ))}
        </div>
      </div>

      {/* 搜素建议结果列表 */}
      <div
        className={classNames('search-result', isSearching ? 'show' : false)}
        hidden={!keyWord}
      >
        {suggestion.map((item, index) => (
          <div
            className="result-item"
            key={index}
            onClick={() => gotoSearchResultPage(item)}
          >
            <Icon className="icon-search" type="iconbtn_search" />
            <div
              className="result-value"
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(highlight(item, keyWord)),
              }}
            >
              {/* <span>{item.keyWord}</span>
              {item.rest} */}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
